import './App.css';
import MachineRoom from './component/MachineRoom';
import React from 'react';
import { getCbinetByName } from './server/Cabinet'
import {
  WebGLRenderer, Scene, PerspectiveCamera, Texture, Mesh, MeshStandardMaterial, Color, MeshBasicMaterial, TextureLoader, Raycaster, Vector2,
} from "three";

//机房对象
let room: MachineRoom;
let canvas: HTMLCanvasElement;

class App extends React.Component {

  curCabinet: string;

  state = {
    planePosi: {
      left: 0,
      top: 100,
    },
    planeDisplay: 'none',
    curCabint: {
      name: 'Load...',
      temperature: 0,//温度
      capacity: 0,//容量
      count: 0,//数量
    }
  };

  componentDidMount() {
    if (canvas == null) return;

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    room = new MachineRoom(canvas, "./models/");
    room.loadGLTF("machineRoom.gltf");

    room.animate();

    room.onMouseEnterEvent = (obj: Mesh, e: { x: number, y: number }) => {
      this.setState({ planeDisplay: 'block', planePosi: { left: e.x, top: e.y, }, });
      obj.position.y += 0.2;
    };
    room.onMouseLeaveEvent = (obj: Mesh, e: {}) => {
      this.setState({ planeDisplay: 'none', });
      obj.position.y -= 0.2;
    };
    room.onMouseMoveEvent = (obj: object, e: { x: number, y: number }) => {
      this.setState({ planePosi: { left: e.x, top: e.y, }, });

      if (this.curCabinet != obj["name"]) {
        getCbinetByName().then(res => {
          this.curCabinet = obj["name"];
          this.setState({
            curCabint: {
              name: obj["name"],
              temperature: res.temperature,//温度
              capacity: res.capacity,//容量
              count: res.count,//数量
            },
          });
        });
      }

    };
  }

  canvasMove({ clientX, clientY }) {
    //这个东西没法在别的类中写, 因为this会指向错误
    room.selectCabinet(clientX, clientY);
  }

  render() {
    const {
      planePosi: { left, top },
      planeDisplay,
      curCabint: { name, temperature, capacity, count }
    } = this.state;

    return (
      <div className="App">
        <canvas id='canvas' ref={(ele) => (canvas = ele)} onMouseMove={this.canvasMove} ></canvas>
        <div id='plane' style={{ left: left, top: top, display: planeDisplay }}>
          <p>机柜名称 : {name}</p>
          <p>机柜温度 : {temperature}°</p>
          <p>使用情况 : {capacity}/{count}</p>
        </div>
      </div>
    );
  }

}

export default App;
